<?php

namespace App\Admin\Controllers\Auth;

use App\Admin\Controllers\Controller;
use App\Admin\Requests\UserCreateRequest;
use App\Admin\Services\AuthService;
use App\Admin\Services\GrantService;
use App\Models\AdminUser;

class AdministratorController extends Controller
{
    protected $authService;
    protected $grantService;

    public function __construct()
    {
        parent::__construct();
        $this->authService  = new AuthService();
        $this->grantService = new GrantService();
    }

    /**
     * 客服列表
     */
    public function index()
    {
        if (request()->expectsJson()) {
            $paginate = $this->authService->users(request('keyword', ''), request('limit', 20));
            return $this->laytable($paginate->total(), $paginate->items());
        }

        return view('admin.administrator.index');
    }

    /**
     * 註冊頁面
     */
    public function create()
    {
        return view('admin.administrator.create', [
            'roles' => $this->grantService->getRoles(),
        ]);
    }

    /**
     * 註冊
     */
    public function store(UserCreateRequest $request)
    {
        $data  = $request->only(['staff_id', 'password', 'name', 'nickname', 'call_id', 'email']);
        $data  = null2char($data);
        $roles = request('roles');
        $roles = explode(',', $roles[0]);
        $roles = $this->grantService->getRoles($roles);

        try {
            $user = $this->authService->register($data);
            if (!($user instanceof AdminUser)) {
                return $this->failure('添加失敗', [], 200);
            }
            $user->syncRoles($roles);
            return $this->success('操作成功', [], 200, broute('admin.index'));
        } catch (\Exception $e) {
            return $this->failure('添加失敗，' . $e->getMessage());
        }
    }

    /**
     * 修改用户
     */
    public function edit()
    {
        $id    = request()->id;
        $admin = $this->authService->user($id);

        // 獲取所有的角色
        $roles = $this->grantService->getRoles();

        // 獲取用户擁有的角色名
        $ownRoles = $admin->getRoleNames()->toArray();

        return view('admin.administrator.edit', [
            'admin'    => $admin,
            'roles'    => $roles,
            'ownRoles' => $ownRoles,
        ]);
    }

    /**
     * 修改用户
     */
    public function update()
    {
        $id    = request()->get('id');
        $roles = request()->get('roles');
        $roles = explode(',', $roles[0]);
        $roles = $this->grantService->getRoles($roles);
        $admin = $this->authService->user($id);

        // 更新用户信息
        $data            = request()->only(['staff_id', 'name', 'nickname', 'enable', 'call_id', 'email']);
        $data['enable']  = $data['enable'] ?? 0;
        $data['call_id'] = $data['call_id'] ?? 0;
        $data['email']   = $data['email'] ?? 0;

        try {
            $this->authService->update($id, $data);
        } catch (\Exception $e) {
            return $this->failure($e->getMessage());
        }

        if ($admin->syncRoles($roles)) {
            return $this->success('操作成功', [], 200, broute('admin.index'));
        }
        return $this->success('操作失敗');
    }

    /**
     * 刪除用户
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function delete()
    {
        $id = request('id');

        if (empty($id)) {
            return $this->failure('未選擇', [], 200);
        }

        if ($this->authService->deleteUsers($id)) {
            return $this->success("刪除成功");
        }

        return $this->failure('刪除失敗');
    }

    /**
     * 一鍵重置密碼成123456
     */
    public function resetPassword($id)
    {
        $password = '123456';

        if ($this->authService->update($id, ['password' => bcrypt($password)])) {
            return $this->success('重置密碼 ' . $password . ' 成功');
        }

        return $this->failure('重置失敗');
    }

}
